package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.dao.CategoryBrandRelationDao;
import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        return categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getCatLevel() == 1)
                .peek(menu -> menu.setChildren(getChildren(menu, categoryEntities)))
                .sorted(Comparator.comparingInt(item -> Optional.ofNullable(item.getSort()).orElse(0)))
                .collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO
        //1、检查当前菜单是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 寻找CategoryId的完整路径
     *
     * @param attrGroupId
     * @return
     */
    @Override
    public Long[] findCategoryPath(Long attrGroupId) {
        List<Long> list = new ArrayList<>();
        getCategoryPath(list, attrGroupId);
//        list.stream().mapToLong(t -> t.longValue()).toArray();  //另外的两种写法 lambda表达式
//        list.stream().mapToLong(Long::new).toArray();
        return list.toArray(new Long[list.size()]);
    }

    /**
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotEmpty(category.getName())) {
            categoryBrandRelationDao.updateCategory(category.getCatId(), category.getName());
            //TODO 可能还要需要更新的三级分类涉及的
        }
    }

    @Override
    public List<CategoryEntity> getLevel1Category() {
        return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>()
                .eq("parent_cid",0));
    }

    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        //1、查出所有一级分类，
        List<CategoryEntity> category = getLevel1Category();
        //2、封装数据
        Map<String, List<Catalog2Vo>> parent_cid = category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、查到这个一级分类下的所有二级分类
            List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq(
                    "parent_cid", v.getCatId()));

            //2、封装上面的结果
            List<Catalog2Vo> catalog2Vos = new ArrayList<>();
            if (categoryEntities != null && categoryEntities.size() != 0) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(
                            l2.getParentCid().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catalog = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq(
                            "parent_cid", l2.getCatId()));
                    List<Catalog2Vo.Catalog3Vo> collectlevel3 = new ArrayList<>();
                    if (level3Catalog != null && !level3Catalog.isEmpty()) {
                        //2、封装成指定格式
                        collectlevel3 = level3Catalog.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l3.getParentCid().toString(),
                                    l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catalog2Vo.setCatalog3List(collectlevel3);
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return parent_cid;
    }

    private void getCategoryPath(List<Long> path, Long attrGroupId) {
        CategoryEntity categoryEntity = baseMapper.selectById(attrGroupId);
        if (categoryEntity != null && categoryEntity.getParentCid() != 0) {
            getCategoryPath(path, categoryEntity.getParentCid());
        }
        path.add(attrGroupId);
    }

    /**
     * 递归获取子分类
     *
     * @param root 分类根
     * @param all  所有的分裂
     * @return 子分类
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .peek(menu -> menu.setChildren(getChildren(menu, all)))
                .sorted(Comparator.comparingInt(item -> Optional.ofNullable(item.getSort()).orElse(0)))
                .collect(Collectors.toList());
    }
}